Coursework 1: Image filtering¶

In this coursework you will practice techniques for image filtering. The coursework includes coding questions and written questions. Please read both the text and the code in this notebook to get an idea what you are expected to implement.

What to do?¶

  • Complete and run the code using jupyter-lab or jupyter-notebook to get the results.

  • Export (File | Save and Export Notebook As...) the notebook as a PDF file, which contains your code, results and answers, and upload the PDF file onto Scientia.

  • Instead of clicking the Export button, you can also run the following command instead: jupyter nbconvert coursework_01_solution.ipynb --to pdf

  • If Jupyter complains about some problems in exporting, it is likely that pandoc (https://pandoc.org/installing.html) or latex is not installed, or their paths have not been included. You can install the relevant libraries and retry. Alternatively, use the Print function of your browser to export the PDF file.

  • If Jupyter-lab does not work for you at the end (we hope not), you can use Google Colab to write the code and export the PDF file.

Dependencies:¶

You need to install Jupyter-Lab (https://jupyterlab.readthedocs.io/en/stable/getting_started/installation.html) and other libraries used in this coursework, such as by running the command: pip3 install [package_name]

In [ ]:
# Import libaries (provided)
import imageio.v3 as imageio
import numpy as np
import matplotlib.pyplot as plt
import noise
import scipy
import scipy.signal
import math
import time

1. Moving average filter (20 points).¶

Read the provided input image, add noise to the image and design a moving average filter for denoising.

You are expected to design the kernel of the filter and then perform 2D image filtering using the function scipy.signal.convolve2d().

In [ ]:
# Read the image (provided)
image = imageio.imread('campus_snow.jpg')
plt.imshow(image, cmap='gray')
plt.gcf().set_size_inches(8, 8)
In [ ]:
# Corrupt the image with Gaussian noise (provided)
image_noisy = noise.add_noise(image, 'gaussian')
plt.imshow(image_noisy, cmap='gray')
plt.gcf().set_size_inches(8, 8)

Note: from now on, please use the noisy image as the input for the filters.¶

1.1 Filter the noisy image with a 3x3 moving average filter. Show the filtering results.¶

In [ ]:
# Design the filter h
### Insert your code ###
h = np.ones((3, 3)) / (3*3)

# Convolve the corrupted image with h using scipy.signal.convolve2d function
### Insert your code ###
image_filtered = scipy.signal.convolve2d(image_noisy, h, "same")

# Print the filter (provided)
print('Filter h:')
print(h)

# Display the filtering result (provided)
plt.imshow(image_filtered, cmap='gray')
plt.gcf().set_size_inches(8, 8)
Filter h:
[[0.11111111 0.11111111 0.11111111]
 [0.11111111 0.11111111 0.11111111]
 [0.11111111 0.11111111 0.11111111]]

1.2 Filter the noisy image with a 11x11 moving average filter.¶

In [ ]:
# Design the filter h
### Insert your code ###
SHAPE = 11
h = np.ones((SHAPE, SHAPE)) / (SHAPE*SHAPE)

# Convolve the corrupted image with h using scipy.signal.convolve2d function
### Insert your code ###
image_filtered = scipy.signal.convolve2d(image_noisy, h, "same")

# Print the filter (provided)
print('Filter h:')
print(h)

# Display the filtering result (provided)
plt.imshow(image_filtered, cmap='gray')
plt.gcf().set_size_inches(8, 8)
Filter h:
[[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
 [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
  0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]]

1.3 Comment on the filtering results. How do different kernel sizes influence the filtering results?¶

Insert your answer¶

The larger the moving average kernel, the more noise seems to be removed - the pixels that are darker in the original are becoming darker as the kernel becomes larger, and vice versa for the light pixels, i.e. the greyscale values seem to be getting closer to the original as the kernel size increases. However the image also becomes more blurry as the kernel size increases.

2. Edge detection (56 points).¶

Perform edge detection using Sobel filtering, as well as Gaussian + Sobel filtering.

2.1 Implement 3x3 Sobel filters and convolve with the noisy image.¶

In [ ]:
# Design the filters
### Insert your code ###
sobel_x = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])
sobel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])

# Image filtering
### Insert your code ###
filtered_x = scipy.signal.convolve2d(image, sobel_x, "same")
filtered_y = scipy.signal.convolve2d(image, sobel_y, "same")

# Calculate the gradient magnitude
### Insert your code ###
grad_mag = np.sqrt((filtered_x * filtered_x) + (filtered_y * filtered_y))

# Print the filters (provided)
print('sobel_x:')
print(sobel_x)
print('sobel_y:')
print(sobel_y)

# plt.imshow(filtered_x, cmap='gray')
# plt.gcf().set_size_inches(8, 8)
# plt.show()
# plt.imshow(filtered_y, cmap='gray')
# plt.gcf().set_size_inches(8, 8)
# plt.show()


# Display the magnitude map (provided)
plt.imshow(grad_mag, cmap='gray')
plt.gcf().set_size_inches(8, 8)
sobel_x:
[[ 1  0 -1]
 [ 2  0 -2]
 [ 1  0 -1]]
sobel_y:
[[ 1  2  1]
 [ 0  0  0]
 [-1 -2 -1]]

2.2 Implement a function that generates a 2D Gaussian filter given the parameter $\sigma$.¶

In [ ]:
# Design the Gaussian filter
def gaussian_filter_2d(sigma):
    # sigma: the parameter sigma in the Gaussian kernel (unit: pixel)
    #
    # return: a 2D array for the Gaussian kernel
    
    ### Insert your code ###
    size = int(2 * np.ceil(2 * sigma) + 1) # Get an odd numbered size based on sigma
    x, y = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]
    h = np.exp(-((x**2 + y**2)/(2*sigma**2)))
    return h/h.sum()

# Visualise the Gaussian filter when sigma = 5 pixel (provided)
sigma = 5
h = gaussian_filter_2d(sigma)
plt.imshow(h)
Out[ ]:
<matplotlib.image.AxesImage at 0x24481555720>

2.3 Perform Gaussian smoothing ($\sigma$ = 5 pixels) and evaluate the computational time for Gaussian smoothing. After that, perform Sobel filtering and show the gradient magintude map.¶

In [ ]:
# Construct the Gaussian filter
### Insert your code ###
sigma = 5
h_gaussian = gaussian_filter_2d(sigma)

# Perform Gaussian smoothing and count time
### Insert your code ###
gaussian_smoothed = scipy.signal.convolve2d(image, h_gaussian, "same")
# plt.imshow(smoothed, cmap='gray', vmin=0, vmax=100)
# plt.gcf().set_size_inches(8, 8)

# Image filtering
### Insert your code ###
filtered_x = scipy.signal.convolve2d(gaussian_smoothed, sobel_x, "same")
filtered_y = scipy.signal.convolve2d(gaussian_smoothed, sobel_y, "same")

# plt.imshow(filtered_x, cmap='gray', vmin=0, vmax=100)
# plt.gcf().set_size_inches(8, 8)
# plt.show()
# plt.imshow(filtered_y, cmap='gray', vmin=0, vmax=100)
# plt.gcf().set_size_inches(8, 8)
# plt.show()

# Calculate the gradient magnitude
### Insert your code ###
grad_mag = np.sqrt((filtered_x * filtered_x) + (filtered_y * filtered_y))

# Display the gradient magnitude map (provided)
plt.imshow(grad_mag, cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)

2.4 Implement a function that generates a 1D Gaussian filter given the parameter $\sigma$. Generate 1D Gaussian filters along x-axis and y-axis respectively.¶

In [ ]:
# Design the Gaussian filter
def gaussian_filter_1d(sigma):
    # sigma: the parameter sigma in the Gaussian kernel (unit: pixel)
    #
    # return: a 1D array for the Gaussian kernel
    
    ### Insert your code ###
    size = int(2 * np.ceil(2 * sigma) + 1)  # Get an odd numbered size based on sigma
    h = np.arange(-size //2 + 1, size // 2 + 1)
    h = np.exp(-h**2 / (2 * sigma**2))
    h = h/h.sum()
    return h[np.newaxis, :]

# sigma = 5 pixel (provided)
sigma = 5

# The Gaussian filter along x-axis. Its shape is (1, sz).
### Insert your code ###
h_x = gaussian_filter_1d(sigma)

# The Gaussian filter along y-axis. Its shape is (sz, 1).
### Insert your code ###
h_y = np.transpose(gaussian_filter_1d(sigma))

# Visualise the filters (provided)
plt.subplot(1, 2, 1)
plt.imshow(h_x)
plt.subplot(1, 2, 2)
plt.imshow(h_y)
Out[ ]:
<matplotlib.image.AxesImage at 0x244928c7460>

2.6 Perform Gaussian smoothing ($\sigma$ = 5 pixels) using two separable filters and evaluate the computational time for separable Gaussian filtering. After that, perform Sobel filtering, show the gradient magnitude map and check whether it is the same as the previous one without separable filtering.¶

In [ ]:
# Perform separable Gaussian smoothing and count time
### Insert your code ###
gaussian_smoothed_x = scipy.signal.convolve2d(image, h_x, "same")
gaussian_smoothed_y = scipy.signal.convolve2d(gaussian_smoothed_x, h_y, "same")

# plt.imshow(smoothed_y, cmap='gray', vmin=0, vmax=100)
# plt.gcf().set_size_inches(8, 8)
# plt.show()

# Image filtering
### Insert your code ###
filtered_x = scipy.signal.convolve2d(gaussian_smoothed_y, sobel_x, "same")
filtered_y = scipy.signal.convolve2d(gaussian_smoothed_y, sobel_y, "same")

# Calculate the gradient magnitude
### Insert your code ###
grad_mag2 = np.sqrt((filtered_x * filtered_x) + (filtered_y * filtered_y))

# Display the gradient magnitude map (provided)
plt.imshow(grad_mag2, cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)

# Check the difference between the current gradient magnitude map
# and the previous one produced without separable filtering. You
# can report the mean difference between the two.
### Insert your code ###
print("mean difference: ", np.mean(grad_mag2 - grad_mag))
mean difference:  -8.967542442278078e-15

2.7 Comment on the Gaussian + Sobel filtering results and the computational time.¶

Insert your answer¶

The 2D filter took on average 1.9s to smooth the image whereas using two 1D filters took on average 0.6s. The Sobel filtering finds fine edges of smaller objects like leaves on the floor, whereas Gaussian + Sobel filtering predominantly highlights the edges of large objects like the statue and mostly smooths out the edges of small objects.

3. Challenge: Implement 2D image filters using Pytorch (24 points).¶

Pytorch is a machine learning framework that supports filtering and convolution.

The Conv2D operator takes an input array of dimension NxC1xXxY, applies the filter and outputs an array of dimension NxC2xXxY. Here, since we only have one image with one colour channel, we will set N=1, C1=1 and C2=1. You can read the documentation of Conv2D for more detail.

In [ ]:
# Import libaries (provided)
import torch

3.1 Expand the dimension of the noisy image into 1x1xXxY and convert it to a Pytorch tensor.¶

In [ ]:
# Expand the dimension of the numpy array
### Insert your code ###
image_noisy_expanded = np.expand_dims(image_noisy, (0, 1))

# Convert to a Pytorch tensor using torch.from_numpy
### Insert your code ###
image_noisy_tensor = torch.from_numpy(image_noisy_expanded)

3.2 Create a Pytorch Conv2D filter, set its kernel to be a 2D Gaussian filter and perform filtering.¶

In [ ]:
# A 2D Gaussian filter when sigma = 5 pixel (provided)
sigma = 5
h = gaussian_filter_2d(sigma)

# Create the Conv2D filter
### Insert your code ###
kernel_size = int(2 * np.ceil(2 * sigma) + 1)
h_tensor = torch.from_numpy(np.expand_dims(h, (0, 1)))  # expand and convert Gaussian filter into tensor

gaussian_kernel_tensor = torch.nn.Conv2d(in_channels=1, out_channels=1, kernel_size=kernel_size)
gaussian_kernel_tensor.weight.data = h_tensor
gaussian_kernel_tensor.weight.requires_grad = False

# Filtering
### Insert your code ###
image_filtered = torch.nn.functional.conv2d(image_noisy_tensor, gaussian_kernel_tensor.weight)

# Display the filtering result (provided)
plt.imshow(torch.squeeze(image_filtered), cmap='gray')
plt.gcf().set_size_inches(8, 8)

3.3 Implement Pytorch Conv2D filters to perform Sobel filtering on Gaussian smoothed images, show the gradient magnitude map.¶

In [ ]:
# Create Conv2D filters
### Insert your code ###
sobel_x_tensor = torch.Tensor([[-1, 0, 1],
                               [-2, 0, 2],
                               [-1, 0, 1]])
sobel_y_tensor = torch.Tensor([[-1, -2, -1],
                               [0, 0, 0],
                               [1, 2, 1]])

sobel_filter_x = torch.nn.Conv2d(1, 1, kernel_size=kernel_size)
sobel_filter_x.weight = torch.nn.Parameter(sobel_x_tensor.unsqueeze(0).unsqueeze(0))

sobel_filter_y = torch.nn.Conv2d(1, 1, kernel_size=kernel_size)
sobel_filter_y.weight = torch.nn.Parameter(sobel_y_tensor.unsqueeze(0).unsqueeze(0))

# Perform filtering
### Insert your code ###
gaussian_kernel_tensor.weight.data = h_tensor.float()

smoothed_image = gaussian_kernel_tensor(image_noisy_tensor.float())

filtered_x = sobel_filter_x(smoothed_image)
filtered_y = sobel_filter_y(smoothed_image)

# plt.imshow(filtered_x.squeeze().detach().numpy(), cmap='gray', vmin=0, vmax=100)
# plt.gcf().set_size_inches(8, 8)
# plt.show()
# plt.imshow(filtered_y.squeeze().detach().numpy(), cmap='gray', vmin=0, vmax=100)
# plt.gcf().set_size_inches(8, 8)
# plt.show()

# Calculate the gradient magnitude map
### Insert your code ###
grad_mag3 = torch.sqrt(torch.pow(filtered_x, 2) + torch.pow(filtered_y, 2))

# Visualise the gradient magnitude map (provided)
plt.imshow(grad_mag3.squeeze().detach().numpy(), cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)
In [ ]: